package com.fans.chapter3.six;

import java.util.Date;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

public class Student implements  Runnable{
	
	private Phaser phaser;
	
	public Student(Phaser phaser) {
		this.phaser = phaser;
	}

	@Override
	public void run() {
		System.out.printf("%s: has arrived to do the exam.%s\n",Thread.currentThread().getName(),new Date());
		phaser.arriveAndAwaitAdvance();

		System.out.printf("%s: is going to do the first exercise %s.\n",Thread.currentThread().getName(),new Date());
		doExceercise1();
		System.out.printf("%s: has down the first exercise %s.\n",Thread.currentThread().getName(),new Date());
		phaser.arriveAndAwaitAdvance();


		System.out.printf("%s: is going to do the second exercise %s.\n",Thread.currentThread().getName(),new Date());
		doExceercise2();
		System.out.printf("%s: has down the second exercise %s.\n",Thread.currentThread().getName(),new Date());
		phaser.arriveAndAwaitAdvance();
		
		System.out.printf("%s: is going to do the third exercise %s.\n",Thread.currentThread().getName(),new Date());
		doExceercise3();
		System.out.printf("%s: has down the second exercise %s.\n",Thread.currentThread().getName(),new Date());

		phaser.arriveAndAwaitAdvance();

	}
	
	private void doExceercise1(){
		long duration = (long)(Math.random()*10);
		try {
			TimeUnit.SECONDS.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private void doExceercise2(){
		long duration = (long)(Math.random()*10);
		try {
			TimeUnit.SECONDS.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	private void doExceercise3(){
		long duration = (long)(Math.random()*10);
		try {
			TimeUnit.SECONDS.sleep(duration);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
